package com.iot08.api.service.supplement;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot08.api.config.redis.RedisClusterService;
import com.iot08.api.config.redis.RedisFilterService;
import com.iot08.api.service.DeviceLocationService;
import com.iot08.api.service.DeviceService;
import com.iot08.api.utils.buckettool.BaseBucketTool;
import com.iot08.api.vo.request.GetMonitoringWatchShopReqVO;
import com.iot08.api.vo.request.MonitoringWatchShopReqVO;
import com.iot08.api.vo.request.NoticePayMentWithDevReqVO;
import com.iot08.api.vo.request.SendVideoAppnetStatusReqVO;
import com.iot08.api.vo.request.base.BaseAccountReqVO;
import com.iot08.common.constant.CacheEnum;
import com.iot08.common.constant.Const;
import com.iot08.common.constant.ConstCacheField;
import com.iot08.common.constant.ConstKafka;
import com.iot08.common.entity.app.Device;
import com.iot08.common.utils.HttpReq;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Description:
 * @time: 2020/11/24 17:17
 * @author: Rock
 */
@Slf4j
@Service
public class CommonService {

    @Resource
    private RedisFilterService redisFilterService;
    @Resource
    private DeviceService deviceService;
    @Resource
    private KafkaService kafkaService;
    @Resource
    private BaseBucketTool baseBucketTool;
    @Resource
    private DeviceLocationService deviceLocationService;

    @Value("${watch.store.channel.url: }")
    private String watchStoreChannelUrl;


    /**
     * @param key
     * @param field
     * @param value
     * @param onlineStatus
     * @param field1
     * @time: 2020/11/24 17:48
     * @author: Rock
     * @version 1.0
     */
    private void setEmitDeviceDemandCache(String key, String field, Map<String, Object> value, String onlineStatus, String field1) {
        RedisClusterService.getJedisCluster().hset(key, field, JSON.toJSONString(value));
        if (!"1".equals(onlineStatus)) {
            RedisClusterService.getJedisCluster().hset(key, field1, "1");
        }
    }

    /**
     * 发送通知设备付款成功的消息
     *
     * @param vo
     * @time: 2020/12/25 17:08
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap noticePayMentWithDev(NoticePayMentWithDevReqVO vo) {
        String onlineStatus = RedisClusterService.getJedisCluster().hget(vo.getImei(), ConstCacheField.ONLINE_STATUS);
        if ("1".equals(onlineStatus)) {
            JSONObject json = new JSONObject();
            json.put("noticeType", vo.getNoticeType());
//            kafkaService.emitDeviceDemand(vo.getImei(), ConstKafka.DEVICE_TYPE_106, json);
        }
        return ResponseMap.success();
    }


    /**
     * 应用监管 设备商店应用权限列表获取
     *
     * @param vo
     * @time: 2020/11/23 17:04
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap getMonitoringWatchShop(GetMonitoringWatchShopReqVO vo) {
        long timestamp = System.currentTimeMillis();
        String authKey = DigestUtils.md5Hex(Const.MD5_KEY + timestamp).toUpperCase();
        String url = String.format("/getway/regulatory?imei=%s&distributors=%s&timestamp=%s&authKey=%s",
                vo.getImei(), vo.getDistributors(), timestamp, authKey);
        String res = HttpReq.sendGet(watchStoreChannelUrl + url, null);
        JSONObject json = JSON.parseObject(res);
        if (json != null && new Integer(200).equals(json.getInteger("code"))) {
            if (json.containsKey("apkList")) {
                ResponseMap responseMap = ResponseMap.success();
                responseMap.put("apkList", json.get("apkList"));
                return responseMap;
            } else {
                log.info("getMonitoringWatchShop is not apkList. url={}; response.json()={}", url, json);
            }
        } else {
            log.info("getMonitoringWatchShop is fail. url={}; response.json()={}", url, json);
        }
        return ResponseMap.fail();
    }

    /**
     * APP修改 设备商店应用权限列表调用的接口, 调用完 会下发给设备,触发设备自定义事件
     *
     * @param vo
     * @time: 2021/1/9 16:17
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap monitoringWatchShop(MonitoringWatchShopReqVO vo) {
        Device device = deviceService.findById(vo.getImei());
        if (device == null) {
            log.error("Device is null. id = {}. monitoringWatchShop vo={}", vo.toString(), vo);
            return ResponseMap.fail(ResponseEnum.STATUS2001.getCode(), ResponseEnum.STATUS2001.getMsg(), vo.getImei());
        }
        Map<String, String> params = new HashMap<>();
        long timestamp = System.currentTimeMillis();
        String authKey = DigestUtils.md5Hex(Const.MD5_KEY + timestamp).toUpperCase();
        params.put("timestamp", timestamp + "");
        params.put("authKey", authKey);
        params.put("imei", vo.getImei());
        params.put("distributors", vo.getDistributors());
        params.put("apkId", vo.getApkId());
        String url = watchStoreChannelUrl + "/getway/regulatory";
        String res = HttpReq.sendPostParam(url, params);
        JSONObject json = JSON.parseObject(res);
        if (json != null && new Integer(200).equals(json.getInteger("code"))) {
            JSONObject kafkaData = new JSONObject();
            kafkaData.put("requestURL", watchStoreChannelUrl + "/getway/regulatory/getDisableApk");
            if (StringUtil.isNotBlank(device.getWatchCustomFunction()) && device.getWatchCustomFunction().contains("APPM:")) {
                String[] temp = device.getWatchCustomFunction().split(":");
                temp = temp[temp.length - 1].split(",");
                kafkaData.put("watchStoreChannelId", temp[0]);
            } else {
                kafkaData.put("watchStoreChannelId", device.getWatchStoreChannelId() == null ? "" : device.getWatchStoreChannelId());
            }
//            kafkaService.emitDeviceDemand(vo.getImei(), ConstKafka.DEVICE_TYPE_104, kafkaData);
            return ResponseMap.success();
        } else {
            log.info("monitoringWatchShop is fail. url={}; response.json()={}", url, json);
        }
        return ResponseMap.fail();
    }

//    /**
//     * 日志的获取是否已上传的信息
//     *
//     * @param uuid
//     * @time: 2021/1/28 10:58
//     * @author: Rock
//     * @version 1.0
//     */
//    public ResponseMap getLogupdateInterface(String uuid) {
//        ResponseMap res = ResponseMap.success();
//        if ("1".equals(redisFilterService.get(CacheEnum.LOG_UPDATE + uuid))) {
//            res.put("type", 2);
//            redisFilterService.del(CacheEnum.LOG_UPDATE + uuid);
//        } else {
//            res.put("type", 0);
//        }
//        return res;
//    }

    /**
     * 上传日志
     *
     * @param openid
     * @param logzipFile
     * @time: 2021/1/28 10:58
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap logupdateInterface(String openid, String userAgent, MultipartFile logzipFile) throws IOException {
        if (StringUtil.isNotBlank(openid) && logzipFile != null && !logzipFile.isEmpty()) {
            String appType = "other/";
            if (StringUtil.isNotBlank(userAgent)) {
                if (userAgent.contains("iOS")) {
                    appType = "iOS/";
                } else if (userAgent.contains("Android")) {
                    appType = "Android/";
                }
            }
            //生成文件名并上传
            String fileName = BaseBucketTool.createFileNameToZip(openid);
            baseBucketTool.upload(BaseBucketTool.APPLOG_COMMON_PATH + appType + fileName, logzipFile, 3);
            ResponseMap res = ResponseMap.success();
            res.put("backShowMsg", String.format("上报异常成功,标识码openid: %s \n 上报时间:%s", openid, fileName.split(openid)[0]));
            return res;
        } else {
            return ResponseMap.fail(ResponseEnum.STATUS403.getCode(), "缺少logzipFile参数");
        }
    }

//    /**
//     * 设置提取 特定UUID 设备的日志
//     *
//     * @param uuid
//     * @time: 2021/1/28 11:00
//     * @author: Rock
//     * @version 1.0
//     */
//    public ResponseMap setuuidwithgetlog(String uuid) {
//        redisFilterService.setex(CacheEnum.LOG_UPDATE.getKey() + uuid, CacheEnum.LOG_UPDATE.getExpire(), "1");
//        return ResponseMap.success();
//    }

    /**
     * @param vo
     * @time: 2021/2/26 11:52
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap getSmallProgramConfig(BaseAccountReqVO vo) {
        ResponseMap res = ResponseMap.success();
        res.put("iconUrl", "http://management.znsh.iot08.com/image/watchShop.png");
        res.put("smallProgramId", "gh_6b91b6733788");
        res.put("smallProgramPath", "");
        res.put("isShow", 0);
        return res;
    }


    @Value("${tempSlideshowJSONArrStr:[] }")
    private String tempSlideshowJSONArrStr;
    /**
     * @param vo
     * @time: 2021/2/26 11:53
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap getSlideshow(BaseAccountReqVO vo) {
        ResponseMap res = ResponseMap.success();
        try{
            String cacheStr = redisFilterService.get("TX:TempSlideshowJSONArrStr");
            if(cacheStr == null){
                cacheStr = tempSlideshowJSONArrStr;
            }
            JSONArray tempSlideshowList = JSONArray.parseArray(cacheStr);
        /*
        slideshow   : [list]
            [
                {
                    id      : [int]
                    title   : [str] //广告标题
                    image   : [str] //图片链接
                    url     : [str] //跳转链接
                },......
            ]
        */
            res.put("slideshow", tempSlideshowList);
        }catch (Exception e){
            res.put("slideshow", new ArrayList<>());
            log.error("get slideshow error"+e.getMessage(), e);
        }

        res.put("bannerPromptTips", new HashMap<>());
        res.put("pageTips", new HashMap<>());
        return res;
    }

    /**
     * @param imei
     * @param vo
     * @time: 2021/3/25 15:31
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap sendVideoAppnetStatus(String imei, SendVideoAppnetStatusReqVO vo) {
        JSONObject kafkaData = new JSONObject();
        kafkaData.put("video_id", vo.getVideo_id());
        kafkaData.put("status", vo.getNetStatus());
        kafkaService.emitDeviceDemand(imei, ConstKafka.DEVICE_TYPE_DownVideoCallNetStatus, kafkaData, vo.getOpenid());
        return ResponseMap.success();
    }

    /**
     * @param filename
     * @param response
     * @time: 2021/3/26 15:45
     * @author: Rock
     * @version 1.0
     */
    public void download(String filename, HttpServletResponse response) throws IOException {
        if (StringUtil.isNotBlank(filename)) {
            String fileType = "audio/AMR";
            String bucketPath = BaseBucketTool.MESSAGE_COMMON_PATH;
            if (filename.contains(".jpg")) {
                bucketPath = BaseBucketTool.PHOTOGRAPH_COMMON_PATH;
                fileType = "image/jpeg";
            }
            if (filename.contains("ppmessage")) {
                bucketPath = BaseBucketTool.PPMESSAGE_COMMON_PATH;
            }
            if(filename.contains("/")){
                // 是否有包含路径, 有包含的直接用
                bucketPath = "";
            }
            ByteArrayOutputStream outputStream = baseBucketTool.downloadFileStream(bucketPath + filename);
            if (outputStream != null) {
                response.setHeader("Content-Type", fileType);
                response.setHeader("Content-Length", String.valueOf(outputStream.size()));
                response.setHeader("Accept-Ranges", "bytes");
                OutputStream os = response.getOutputStream();
                os.write(outputStream.toByteArray());
                os.flush();
                outputStream.close();
                os.close();
            } else {
                log.warn("文件下载失败：url = {}", bucketPath + filename);
            }
        }
    }
//
//    public void miniIO(String filename, HttpServletResponse response) throws IOException {
//        if (StringUtil.isNotBlank(filename)) {
//            String fileType = "audio/AMR";
//            String ossPath = BaseBucketTool.MESSAGE_COMMON_PATH;
//            if (filename.contains(".jpg")) {
//                ossPath = BaseBucketTool.PHOTOGRAPH_COMMON_PATH;
//                fileType = "image/jpeg";
//            }
//            if (filename.contains("ppmessage")) {
//                ossPath = BaseBucketTool.PPMESSAGE_COMMON_PATH;
//            }
//            ByteArrayOutputStream outputStream = baseBucketTool.downloadFileStream(ossPath + filename);
//            if (outputStream != null) {
//                response.setHeader("Content-Type", fileType);
//                response.setHeader("Content-Length", String.valueOf(outputStream.size()));
//                response.setHeader("Accept-Ranges", "bytes");
//                OutputStream os = response.getOutputStream();
//                os.write(outputStream.toByteArray());
//                os.flush();
//                outputStream.close();
//                os.close();
//            } else {
//                log.warn("MiniIO 文件下载失败：url = {}", ossPath + filename);
//            }
//        }
//    }
}
